package main

import (
	"flag"
	"fmt"
	"github.com/panjf2000/gnet"
	"log"
)

type echoServer struct {
	*gnet.EventServer
}

func (es *echoServer) OnInitComplete(srv gnet.Server) (action gnet.Action) {
	log.Printf("Echo server is listening on %s (multi-cores: %t, loops: %d)\n",
		srv.Addr.String(), srv.Multicore, srv.NumEventLoop)
	return
}

/*****
* 服务器关机时需要执行的操作，需要关闭所有连接
 */
func (es *echoServer) OnShutdown(srv gnet.Server) {

}

func (es *echoServer) OnOpened(c gnet.Conn) (out []byte, action gnet.Action) {
	log.Printf("new client connected to %s", c.RemoteAddr().String())

	/*strArr := strings.Split(c.RemoteAddr().String(), ":")
	var ci ConnInfo
	ci.conn = c
	if len(strArr) == 2 {
		ci.connIp = strArr[0]
		ci.connPort = strArr[1]
	}
	connMap.Set()*/
	out = []byte("AT+KEY=?\r\n")
	return
}

func (es *echoServer) OnClosed(c gnet.Conn, err error) (action gnet.Action) {
	log.Printf("client %s is closed", c.RemoteAddr().String())
	return
}

func (es *echoServer) React(frame []byte, c gnet.Conn) (out []byte, action gnet.Action) {
	// Echo synchronously.
	out = frame
	log.Printf("tcp server recv from %s to %s,data is %s", c.RemoteAddr().String(), c.LocalAddr().String(), string(out))
	return

	/*
		// Echo asynchronously.
		data := append([]byte{}, frame...)
		go func() {
			time.Sleep(time.Second)
			c.AsyncWrite(data)
		}()
		return
	*/
}

func tcpServerEcho() {
	var port int
	var multicore bool

	// Example command: go run echo.go --port 9000 --multicore=true
	flag.IntVar(&port, "port", 9001, "--port 9001")
	flag.BoolVar(&multicore, "multicore", true, "--multicore true")
	flag.Parse()
	echo := new(echoServer)
	log.Fatal(gnet.Serve(echo, fmt.Sprintf("tcp://:%d", port), gnet.WithMulticore(multicore)))
}
